package cn.Alibaba.basic.util;

import cn.Alibaba.basic.jwt.JwtUtils;
import cn.Alibaba.basic.jwt.LoginData;
import cn.Alibaba.basic.jwt.Payload;
import cn.Alibaba.basic.jwt.RsaUtils;
import cn.Alibaba.user.domain.Logininfo;

import javax.servlet.http.HttpServletRequest;
import java.security.PublicKey;

public class LoginContext {

    public static Logininfo getLoginUser(HttpServletRequest request){

        // 从请求头里拿到token
        String token = request.getHeader("token");

        if (token!=null){

            try {
                // 获取公钥
                PublicKey publicKey = RsaUtils.getPublicKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pub").getFile());

                // 在解密
                Payload<LoginData> payload = JwtUtils.getInfoFromToken(token, publicKey, LoginData.class);

                return payload.getLoginData().getLogininfo();

            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        return null;

    }
}
